/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年4月7日         Root.Lu
 */

package com.coocaa.x.service.litecontent;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;

import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.data.ResultPackage;
import com.coocaa.x.service.litecontent.tools.KVCache;

import java.util.HashMap;
import java.util.Map;

public abstract class LiteContentProvider {
    private static final String URI_FORMAT = "%s://%s%s";
    public static final Map<String, ResourceHandler> rhs = new HashMap<String, ResourceHandler>();

    public static abstract class LiteContentProviderHost {
        private LiteContentProvider parentProvider = null;
        protected Context mContext = null;

        public LiteContentProviderHost(Context context, LiteContentProvider provider) {
            parentProvider = provider;
            mContext = context;
        }

        public LiteContentProvider getParentProvider() {
            return parentProvider;
        }

        public abstract String myHost();

        protected static void runOnUiThread(Runnable run) {
            AsyncTask.runOnUiThread(run);
        }
    }

    public static abstract class ResourceHandler {
        public static Context mContext = null;
        private static KVCache<String, String> kvCache = null;
        private String uri_path = null;
        private KVCache<String, String> mKVCache = null;

        public ResourceHandler(LiteContentProviderHost host, String path) {
            String _scheme = host.getParentProvider().myScheme();
            String _host = host.myHost();
            uri_path = String.format(URI_FORMAT, _scheme, _host, path);
            synchronized (rhs) {
                rhs.put(uri_path, this);
                LogUtils.i("LCP", "ResourceHandler add " + uri_path);
            }
            if (kvCache == null) {
                kvCache = new KVCache<String, String>() {
                    private SharedPreferences sp = mContext.getSharedPreferences(
                            "content_provider_kvcache", Context.MODE_WORLD_READABLE
                                    + Context.MODE_WORLD_WRITEABLE);

                    @Override
                    public String get(String key) {
                        return sp.getString(key, "");
                    }

                    @Override
                    public boolean save(String key, String value) {
                        Editor editor = sp.edit();
                        editor.putString(key, value);
                        return editor.commit();
                    }

                    @Override
                    public boolean contains(String key) {
                        return sp.contains(key);
                    }

                    @Override
                    public boolean remove(String key) {
                        Editor editor = sp.edit();
                        editor.remove(key);
                        return editor.commit();
                    }
                };
            }

            mKVCache = new KVCache<String, String>() {
                @Override
                public String get(String key) {
                    return kvCache.get(myUri() + "@" + key);
                }

                @Override
                public boolean save(String key, String value) {
                    return kvCache.save(myUri() + "@" + key, value);
                }

                @Override
                public boolean contains(String key) {
                    return kvCache.contains(myUri() + "@" + key);
                }

                @Override
                public boolean remove(String key) {
                    return kvCache.remove(myUri() + "@" + key);
                }
            };
            onInit();
        }

        protected void onInit() {
        }

        public abstract ResultPackage call(Uri uri);

        protected final String myUri() {
            return uri_path;
        }

        protected final void sendNotify(String data) {
            LiteContentProvider.sendNotify(myUri(), data);
        }

        protected final KVCache<String, String> getKVCache() {
            return mKVCache;
        }
    }

    protected Context mContext = null;
    private static ILiteContentServiceNotify notify = null;

    public static void setLiteContentServiceNotify(ILiteContentServiceNotify notify) {
        LiteContentProvider.notify = notify;
    }

    public LiteContentProvider(Context context) {
        mContext = context;
    }

    public final ResultPackage call(Uri uri) throws Exception {
        ResultPackage rp = null;
        String _scheme = uri.getScheme();
        String _host = uri.getHost();
        String _path = uri.getPath();
        String uri_path = String.format(URI_FORMAT, _scheme, _host, _path);
        ResourceHandler rh = null;
        synchronized (rhs) {
            rh = rhs.get(uri_path);
        }
        if (rh != null)
            rp = rh.call(uri);
        else {
            // 如果未对uri定制处理，则直接转发给系统处理
            rp = new ResultPackage();
            try {
                Intent it = new Intent("coocaa.intent.action.VIEW", uri);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(it);
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception(e.getMessage());
            }
        }
        return rp;
    }

    public static final void sendNotify(String uri, String data) {
        if (notify != null)
            notify.sendNotify(uri, data);
    }

    public abstract String myScheme();
}
